package com.vimi8.ebb.api.ebb;

import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.dto.LogisticsBusinessDTO1;
import com.vimi8.ebb.dto.LogisticsDTO;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.EnumCategoryService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.LogisticsService;
import com.vimi8.ebb.util.GeoCodingUtil;
import com.vimi8.ebb.util.PagesUtil;
import com.vimi8.ebb.util.SubStringUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 物流信息
 * Created by xiehuang on 2017/1/19.
 */

@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-12T05:17:54.080Z")
@Controller
public class LogisticsFrontApiController implements LogisticsFrontApi {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger("LogisticsFrontApiController");
    @Autowired
    private LogisticsService logisticsService;
    @Autowired
    private EnumCategoryService enumCategoryService;
    @Autowired
    private GeoCodingsService geoCodingsService;

    @Override
    public HttpResponseEntity<Paginator<List<LogisticsBusinessDTO1>>> getLogistics(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "start", required = true) int start,
            @ApiParam(value = "每页大小", required = true) @RequestParam(value = "size", required = true) int size,
            @ApiParam(value = "地址编码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "网点名称", required = false) @RequestParam(value = "branchName", required = false) String branchName,
            @ApiParam(value = "按员工人数排序（asc表示升序，desc表示降序）", required = false) @RequestParam(value = "staffsOrder", required = false) String staffsOrder,
            @ApiParam(value = "按统计日期排序（asc表示升序，desc表示降序）", required = false) @RequestParam(value = "statisticsTimeOrder", required = false) String statisticsTimeOrder
    ) {
        logger.info("requestUrl=" + "/front/logistics/");
        String code = "";
        if (null != addressCode && !"".equals(addressCode)) {
            GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(addressCode);
            code = SubStringUtil.separateGeoCodeByProduct(addressCode, geoCodings.getRegionLever() + 1 + "");
        }
        //获取物流信息的总数
        int count = logisticsService.getLogisticsLatestCount(code, branchName, "","");
        //分页查询物流信息
        List<LogisticsBusinessDTO1> logisticsBusinessDTO1s = logisticsService.getLogisticsLatest((start - 1) * size, size, code, branchName, "","", staffsOrder, statisticsTimeOrder);
        for (LogisticsBusinessDTO1 logisticsBusinessDTO1 : logisticsBusinessDTO1s) {
            EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(logisticsBusinessDTO1.getAffiliationId());//根据ID查询机构信息
            if (!StringUtils.isEmpty(enumCategory)) {
                logisticsBusinessDTO1.setAffiliationName(enumCategory.getCategoryName());//设置机构名称
            }
            String branchAddress = geoCodingsService.getAddressWhole(logisticsBusinessDTO1.getBranchAddressCode());//获取完整地址
            logisticsBusinessDTO1.setBranchAddress(branchAddress);
            String deliveryArea = geoCodingsService.getAddressWhole(logisticsBusinessDTO1.getDeliveryAreaCode());//获取完整地址
            logisticsBusinessDTO1.setDeliveryArea(deliveryArea);
        }
        //设置分页信息
        PagesUtil pagesUtil = new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setTotalCount(count);
        Paginator<List<LogisticsBusinessDTO1>> paginator = new Paginator<List<LogisticsBusinessDTO1>>(start, size, pagesUtil.getTotalPage(), count, logisticsBusinessDTO1s);
        return new HttpResponseEntity<Paginator<List<LogisticsBusinessDTO1>>>(paginator, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<LogisticsDTO> getLogisticsById(@ApiParam(value = "id", required = true) @PathVariable(value = "id", required = true) String id) {
        logger.info("requestUrl=" + "/front/logistics/{id}");
        Logistics logistics = logisticsService.getLogisticsById(id);
        EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(logistics.getAffiliationId());
        LogisticsDTO logisticsDTO = new LogisticsDTO();
        logisticsDTO.fill(logistics);
        if (!StringUtils.isEmpty(enumCategory)) {
            logisticsDTO.setAffiliationName(enumCategory.getCategoryName());
        }
        String branchAddress = geoCodingsService.getAddressWhole(logistics.getBranchAddressCode());//获取完整地址
        logisticsDTO.setBranchAddress(branchAddress);
        String shippingAddress = geoCodingsService.getAddressWhole(logistics.getShippingAddressCode());//获取完整地址
        logisticsDTO.setShippingAddress(shippingAddress);
        String deliveryArea = geoCodingsService.getAddressWhole(logistics.getDeliveryAreaCode());//获取完整地址
        logisticsDTO.setDeliveryArea(deliveryArea);
        return new HttpResponseEntity<LogisticsDTO>(logisticsDTO, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<Object> getLogisticsAnalysis(
            @ApiParam(value = "地址编码", required = true) @RequestParam(value = "addressCode", required = true) String addressCode,
            @ApiParam(value = "统计时间(如：2016-12-01)", required = true) @RequestParam(value = "tradeStatisticsTime", required = true) String tradeStatisticsTime
    ) {
        Error error = new Error();
        if (StringUtils.isEmpty(addressCode)) {
            error.error("参数addressCode必需传递。");
            return new HttpResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
        }
        if (StringUtils.isEmpty(tradeStatisticsTime)) {
            error.error("参数tradeStatisticsTime必需传递。");
            return new HttpResponseEntity<Object>(error, HttpStatus.BAD_REQUEST);
        }
        Map<String, List<Object>> result = new HashMap();//返回值
        Calendar calendar = Calendar.getInstance();
        //如果传递时间参数，则将其转换为日历格式
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(tradeStatisticsTime);
            calendar.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        GeoCodings geoCodings = null;
        try {
            //将区域ID转换为区域对象
            geoCodings = GeoCodingUtil.convertById(addressCode);
        } catch (Exception e) {
            error.error("服务器错误。");
            return new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        //查询当前区域的下一级区域
        List<GeoCodings> geoCodingses = geoCodingsService.getGeoCodings(geoCodings.getId(), geoCodings.Next(), geoCodings.getRegionLever() + 1);
        List<Object> monthOutAmounts = new ArrayList<>();//月发出量列表
        List<Object> monthInAmounts = new ArrayList<>();//月发入量列表
        List<Object> addresses = new ArrayList<>();//地址列表
        List<Object> monthOnMonthsOutAmounts = new ArrayList<>();//环比列表
        List<Object> monthOnMonthsInAmounts = new ArrayList<>();//环比列表
        List<Object> yearOnYearsOutAmounts = new ArrayList<>();//同比列表
        List<Object> yearOnYearsInAmounts = new ArrayList<>();//同比列表


        int currentYear = calendar.get(Calendar.YEAR);//当前日期对应的年份
        int currentMonth = calendar.get(Calendar.MONTH);//当前日期对应的月份

        calendar.add(Calendar.MONTH, -1); // 月份减1
        int currentLastMonth = calendar.get(Calendar.MONTH);//当前日期对应的上一月的月份

        calendar.add(Calendar.YEAR, -1); // 年份减1
        int lastYear = calendar.get(Calendar.YEAR);//当前日期对应的上一年的年份

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        calendar.set(currentYear, currentMonth, 1);
        String currentYearDate = sdf.format(calendar.getTime());//当前日期

        calendar.set(lastYear, currentMonth, 1);
        String lastYearDate = sdf.format(calendar.getTime());//当前日期月份对应的上一年同月的日期

        calendar.set(currentYear, currentLastMonth, 1);
        String currentYearLastDate = sdf.format(calendar.getTime());//当前日期对应的上一个月的日期

        for (GeoCodings geo : geoCodingses) {
            addresses.add(geo);
            //统计当前区域下的物流信息
            HashMap<String, Object> map = logisticsService.getLogisticsAnalysis(geo.getId(), geo.Next(), currentYearDate);
            if (map != null) {
                monthOutAmounts.add(map.get("monthOutAmount"));
                monthInAmounts.add(map.get("monthInAmount"));
            }

            HashMap<String, Object> map1 = logisticsService.getLogisticsAnalysis(geo.getId(), geo.Next(), lastYearDate);
            if (map != null && map1 != null) {
                //同比(月发出量列表)
                double monthOutAmountRate = map1.get("monthOutAmount") != null && !map1.get("monthOutAmount").toString().equals("0") ? Double.parseDouble(map.get("monthOutAmount").toString()) / Double.parseDouble(map1.get("monthOutAmount").toString()) : 0;
                yearOnYearsOutAmounts.add(monthOutAmountRate);
                //同比(月发入量列表)
                double monthInAmountRate = map1.get("monthInAmount") != null && !map1.get("monthInAmount").toString().equals("0") ? Double.parseDouble(map.get("monthInAmount").toString()) / Double.parseDouble(map1.get("monthInAmount").toString()) : 0;
                yearOnYearsInAmounts.add(monthInAmountRate);
            }

            HashMap<String, Object> map2 = logisticsService.getLogisticsAnalysis(geo.getId(), geo.Next(), currentYearLastDate);
            java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
            if (map != null && map2 != null) {
                //环比(月发出量列表)
                double monthOutAmountRate = map2.get("monthOutAmount") != null && !map2.get("monthOutAmount").toString().equals("0") ? Double.parseDouble(map.get("monthOutAmount").toString()) / Double.parseDouble(map2.get("monthOutAmount").toString()) : 0;
                if (!StringUtils.isEmpty(monthOutAmountRate)) {
                    monthOutAmountRate = Double.valueOf(df.format(monthOutAmountRate));
                }
                monthOnMonthsOutAmounts.add(monthOutAmountRate);
                //环比(月发入量列表)
                double monthInAmountRate = map2.get("monthInAmount") != null && !map2.get("monthInAmount").toString().equals("0") ? Double.parseDouble(map.get("monthInAmount").toString()) / Double.parseDouble(map2.get("monthInAmount").toString()) : 0;
                if (!StringUtils.isEmpty(monthInAmountRate)) {
                    monthInAmountRate = Double.valueOf(df.format(monthInAmountRate));
                }
                monthOnMonthsInAmounts.add(monthInAmountRate);
            }
        }
        result.put("monthOutAmounts", monthOutAmounts);//设置月发出量列表
        result.put("monthInAmounts", monthInAmounts);//设置月发入量列表
        result.put("address", addresses);//设置对应的地址列表
        result.put("yearOnYearsOutAmounts", yearOnYearsOutAmounts);//设置同比(月发出量列表)
        result.put("yearOnYearsInAmounts", yearOnYearsInAmounts);//设置同比(月发入量列表)
        result.put("monthOnMonthsOutAmounts", monthOnMonthsOutAmounts);//设置环比(月发出量列表)
        result.put("monthOnMonthsInAmounts", monthOnMonthsInAmounts);//设置环比(月发入量列表)
        return new HttpResponseEntity<Object>(result, HttpStatus.OK);
    }

    @Override
    public HttpResponseEntity<Object> getLogisticsBusinessAnalysis(
            @ApiParam(value = "地址编码", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
            @ApiParam(value = "年-月（如：2017-01）", required = false) @RequestParam(value = "yearAndMonth", required = false) String yearAndMonth,
            @ApiParam(value = "年份", required = false) @RequestParam(value = "year", required = false) String year,
            @ApiParam(value = "季度", required = false) @RequestParam(value = "quarter", required = false) String quarter
    ) {
        Error error = new Error();
        if (!StringUtils.isEmpty(addressCode)) {
            GeoCodings geoCodings = GeoCodingUtil.convertById(addressCode);//将地址编码转换为GeoCodings
            addressCode = GeoCodingUtil.separateAddressCode(addressCode, geoCodings.getRegionLever());//根据地址编码和城市级别将地址编码转换为含通配符的字符串
            logger.info("address_detail="+addressCode);
            logger.info("geoCodings.getRegionLever()="+geoCodings.getRegionLever());
        }
        List<HashMap<String,Object>> results=logisticsService.getLogisticsBusinessAnalysis(addressCode,yearAndMonth,year,quarter);
        return new HttpResponseEntity<Object>(results, HttpStatus.OK);
    }

}
